Page({
  data: {
    phone: '',
    canLogin: false
  },

  onInput(e) {
    const phone = e.detail.value;
    this.setData({
      phone,
      canLogin: phone.length === 11
    });
  },

  async login() {
    if (!this.data.canLogin) return;

    const { phone } = this.data;
    console.log('开始调用云函数 login');
    wx.login({
      success: (res) => {
        wx.cloud.callFunction({
          name: 'login',
          data: { 
            phone,
            code:res.code
           },
          success: res => {
            if (res.result.success) {
              console.log(res)
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 2000
              })
              ;
              wx.setStorageSync('phone', phone);
              wx.setStorageSync('openid', res.result.openid)
              setTimeout(() => {
                console.log("跳转")
                wx.reLaunch({
                  url: '/pages/market/market'
                });
              }, 2000);
            } else {
              console.log("登录失败: 未知原因");
              wx.showToast({
                title: '登录失败',
                icon: 'error',
                duration: 2000
              });
            }
          },
          fail: err => {
            console.log('云函数 login 调用失败', err);
            wx.showToast({
              title: '登录失败',
              icon: 'error',
              duration: 2000
            });
          }
        });
      },
    })
  }
});
